package org.jiajie.coffeecodes.ws;

import javax.websocket.*;
import java.net.URI;
import java.util.Scanner;

@ClientEndpoint
public class Client {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println(session.getId()+"客户端连接");
    }

    @OnClose
    public void onClose() {
        System.out.println("client关闭");
    }

    @OnMessage
    public void onMessage(String msg, Session session) {
        System.out.println("client" + session.getId() + "接收到的消息:" + msg);
    }

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            Session session = container.connectToServer(Client.class, URI.create("ws://service.jagachina.com:41708/echo"));
            //控制台输入消息
            Scanner scanner = new Scanner(System.in);
            String msg;
            //输入quit退出
            while (!"quit".equals(msg = scanner.nextLine())) {
                session.getBasicRemote().sendText(msg);
            }
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}